package com.ljx.thread.thread05;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2022/10/31 14:59
 * @Version 1.0
 */
public class TicketThread2 implements Runnable{


	Lock lock1=new ReentrantLock();
	/**
	 定义票数
 	 */
	private int ticket=100;
	/**
	 * 自动锁
 	 */
	@Override
	public void run() {

		while (true){
			try {
				// 手动上锁
				lock1.lock();
				Thread.sleep(100);
				if (ticket>0){
					// 如果票数大于0 就继续买票否则就结束买票
					System.out.println(Thread.currentThread().getName()+"卖出一张票剩余"+--ticket);
				} else {
					System.out.println(Thread.currentThread().getName()+"没票了，sorry");
					break;
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				// 去锁
				lock1.unlock();
			}
		}


	}
}
